package java_class_work.week08.internet.chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * @Author Tiam
 * @Date 2022/10/31 18:00
 * @Description:
 */
public class User1 implements Runnable {
    DatagramSocket ds = null;

    @Override
    public void run() {
        System.out.println(receiveMessage());
        sendMessage();

    }

    /**
     * 发送消息
     */
    private void sendMessage() {
        try {
            // 1. 新建服务
            ds = new DatagramSocket();
            // 2. 输入数据
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String message = null;
            System.out.print("请输入:");
            while ((message = br.readLine()) != null) {
                if ("over".equalsIgnoreCase(message)) break;
                // 3. 封装数据 和发送地址到 dp
                DatagramPacket dp = new DatagramPacket(message.getBytes(), message.length(), InetAddress.getByName("127.0.0.1"), 8888);
                // 4. 发送数据
                ds.send(dp);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 5. 关闭服务
            if (ds != null) ds.close();
        }
    }

    /**
     * 接收消息
     *
     * @return
     */
    private String receiveMessage() {
        String message = null;
        try {
            // 1. 新建服务
            ds = new DatagramSocket(8888);
            // 2. 接收消息, 封装获取到的消息
            byte[] bytes = new byte[1024];
            DatagramPacket dp = new DatagramPacket(bytes, bytes.length);

            // InetAddress address = dp.getAddress();
            // System.out.println("发送端信息:" + address.toString());
            byte[] data = dp.getData();
            message = new String(data, 0, dp.getLength());
        } catch (SocketException e) {
            e.printStackTrace();
        } finally {
            // 3. 关闭服务
            if (ds != null) ds.close();
        }
        return message;
    }
}
